// The Application
// ---------------

// Our overall **AppView** is the top-level piece of UI.
Todo.View.App = Backbone.View.extend({

    // Instead of generating a new element, bind to the existing skeleton of
    // the App already present in the HTML.
    el        : $("#toddo-app"),


    // Delegated events for creating new items, and clearing completed ones.
    events    : {
        "renderCategory"         : "renderCategory",
        "createItem #newitem"    : "createItem",
        "createItem"             : "createItem",
        "createCategory #newitem": "createCategory",
        "createCategory"         : "createCategory"
    },

    // At initialization we bind to the relevant events on the `Todos`
    // collection, when items are added or changed. Kick things off by
    // loading any preexisting todos that might be saved in *localStorage*.
    initialize: function () {
        if (Todo.debug) {
            console.log('Todo.View.App::initialize');
        }

        this.initModels();
    },

    initModels      : function () {
        this.newItem = new Todo.View.NewItem();

        this.items = Todo.items = new Todo.Collection.Item({
            localStorage: new Backbone.LocalStorage("todo-items")
        });

        this.items.fetch();

        this.categories = Todo.categories = new Todo.Collection.Category({
            localStorage: new Backbone.LocalStorage("todo-category")
        });

        this.categories.fetch();

        if (!this.categories.length) {
            this.categories.create({
                id  : 0,
                name: null
            });
        }
    },

    // Re-rendering the App just means refreshing the statistics -- the rest
    // of the app doesn't change.
    render          : function () {
        if (Todo.debug) {
            console.log('Todo.View.App::render');
        }

        this.renderCategories();
    },

    // Add a single todo item to the list by creating a view for it, and
    // appending its element to the `<ul>`.
    renderCategory  : function (e, category) {
        if (Todo.debug) {
            console.log('Todo.View.App::renderCategory');
        }

        var view = new Todo.View.Category({
            model: category
        });

        this.$("#lists").append(view.render().el);
    },

    // Add all items in the **Todos** collection at once.
    renderCategories: function () {
        if (Todo.debug) {
            console.log('Todo.View.App::renderCategories');
        }

        var $el = this.$el;

        this.$("#lists").empty();

        this.categories.each(function (category) {
            $el.trigger('renderCategory', category)
        });
    },

    createItem: function (e, name) {
        name = $.trim(name);

        var t = name.match(/(.*)+[@](.*)+/);

        var category = null;

        if (t !== null && t[2] != '') {
            name = $.trim(t[1]);
            var categoryName = $.trim(t[2]);
            category = this.categories.isNameExists(categoryName);

            if (!category) {
                this.$el.trigger('createCategory', categoryName);

                category = this.categories.last();
            }
        }

        var currentItem = this.items.isNameExists(name);

        // don't allow duplicate items
        if (currentItem) {
            //move to another category
            if (category && currentItem.get('category_id') != category.id) {
                var oldCategory = this.categories.get(currentItem.get('category_id') || 0);
                console.log(currentItem);

                currentItem.save({"category_id": category.id});

                if (oldCategory) {
                    oldCategory.trigger('updateItems');
                }

                category.trigger('updateItems');
            }
            return;
        }

        var item = {
            name: name
        };

        if (category) {
            item.category_id = category.id;
        }

        var t = this.items.create(item);

        var categoryId = t.get('category_id') || 0;
        var category = this.categories.get(categoryId);

        if (category) {
            category.trigger('updateItems');
        }
    },

    createCategory: function (e, name) {
        name = $.trim(name);

        // don't allow duplicate categories
        if (this.categories.isNameExists(name)) {
            return;
        }

        var t = this.categories.create({
            name: name
        });

        this.$el.trigger('renderCategory', t);

        return t;
    }
});